package org.lcc.Service.impl;

import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.lcc.Service.ExaminationmanagementService;
import org.lcc.Service.MailService;
import org.lcc.mapper.ExaminationmanagementMapper;
import org.lcc.model.VO.*;
import org.lcc.model.dto.*;
import org.lcc.model.entity.*;

import org.lcc.model.entity.Class;
import org.lcc.model.request.AddExamQuestionRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ExaminationmanagementServiceImpl implements ExaminationmanagementService {
    @Autowired
    private ExaminationmanagementMapper examinationmanagementMapper;
    @Autowired
    private MailService mailService;
    @Autowired
    private ObjectMapper objectMapper; // Jackson的对象映射器


    //创建考试
    @Override
    @Transactional

    public Integer createExam(ExamDto examDto) {
        Exam exam = new Exam(
                null,
                examDto.getExamName(),
                examDto.getSubject(),
                examDto.getStartTime(),
                examDto.getDuration(),
                examDto.getTotalScore(),
                examDto.getTeacherId(),
                "待添加试题",
                LocalDateTime.now()
        );
        Integer i = examinationmanagementMapper.createExam(exam);
        if (i <= 0) {
            return null;
        }
        return exam.getExamId();
    }

    //查询题库
    @Override
    public List<QuestionVO> showExam(String schoolNumber) {
        List<QuestionVO> questionVOList = examinationmanagementMapper.getQuestionSummaryBySchoolNumber(schoolNumber);
        // 为每个题库设置编号
        for (int i = 0; i < questionVOList.size(); i++) {
            QuestionVO questionVO = questionVOList.get(i);
            questionVO.setQuestionId(i + 1); // 编号从1开始
        }
        return questionVOList;
    }

    //查询题库各类题型数量等信息
    @Override
    public List<QuestionDataVo> getNumberOfDifferentTypes(String questionName) {
        try {
            return examinationmanagementMapper.getNumberOfDifferentTypes(questionName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询题库各类题型数量等信息失败");
        }
    }

    //根据用户传递的题量信息随机组题
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean randomQuestion(QuestionBankDto questionBankDto, Integer examId) {
        if (questionBankDto == null || examId == null) {
            return false;
        }
        String questionName = questionBankDto.getQuestionName(); // 获取题库名称
        List<QuestionTypeConfigDto> questionTypeConfigsDto = questionBankDto.getQuestionTypeConfigs(); // 获取题型配置列表

        for (QuestionTypeConfigDto config : questionTypeConfigsDto) {
            String type = config.getType(); // 获取题目类型
            Map<String, Integer> difficultyLevels = config.getDifficulty(); // 获取难度等级及其数量

            for (Map.Entry<String, Integer> entry : difficultyLevels.entrySet()) {
                String difficulty = entry.getKey(); // 当前难度等级
                int needCount = entry.getValue(); // 当前难度等级所需的题目数量
                Integer score = config.getScore(); // 当前难度等级的题目分数

                // 调用数据库方法随机获取题目
                List<Integer> questions = examinationmanagementMapper.randomQuestion(
                        questionName, // 题库名称
                        type, // 题目类型
                        difficulty, // 难度等级
                        needCount // 需要的题目数量
                );

                // 如果获取到的题目数量不足，抛出异常
                if (questions.size() < needCount) {
                    throw new RuntimeException("题目数量不足，题库：" + questionName
                            + " 类型：" + type + " 难度：" + difficulty);
                }

                // 将获取到的题目ID传递到插入数据库的方法中
                Integer i = examinationmanagementMapper.insertExam_question(examId, questions, score);
                if (i != questions.size()) {
                    throw new RuntimeException("插入题目数量与预期不符，事务回滚");
                }
            }
        }
        //更新题库状态为待发布
        boolean b = updateExamStatus("待发布", examId);
        if (!b) {
            throw new RuntimeException("更新题库状态为<待发布>失败");
        }
        return true;
    }

    ////根据题库题型显示题目供用户手动选择
    public List<QuestionTypemanualVo> getManualQuestion(String questionName) {
        if (questionName == null) {
            return null;
        }

        List<ManualDto> questions = examinationmanagementMapper.getManualQuestionsByQuestionName(questionName);
        if (questions == null) {
            return null;
        }

        // 2. 按题型分组
        Map<String, List<ManualDto>> typeGroupMap = questions.stream()
                .collect(Collectors.groupingBy(ManualDto::getType));

        return typeGroupMap.entrySet().stream().map(entry -> {
            String type = entry.getKey();
            List<ManualDto> manualDtos = entry.getValue();
            return new QuestionTypemanualVo(type, manualDtos, manualDtos.size());
        }).collect(Collectors.toList());
    }


    //手动选题
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean manualQuestion(Integer examId, QuestionIdDto questionId) {
        System.out.println(questionId);
        try {
            for (Map<String, Integer> integerIntegerMap : questionId.getQuestion_id()) {
                for (Map.Entry<String, Integer> entry : integerIntegerMap.entrySet()) {
                    Integer questionId1 = Integer.parseInt(entry.getKey());
                    Integer score = entry.getValue();
                    Integer i = examinationmanagementMapper.insertExam_question(examId, Collections.singletonList(questionId1), score);
                    if (i != 1) {
                        throw new RuntimeException("插入题目数量与预期不符，事务回滚");
                    }
                }
            }
            //更新题库状态为待发布
            boolean b = updateExamStatus("待发布", examId);
            if (!b) {
                throw new RuntimeException("更新题库状态为<待发布>失败");
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("手动添加题目失败", e);
        }
    }

    //发布考试
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PublishExamResultDto publishExam(PubishExamDto pub) {
        PublishExamResultDto result = new PublishExamResultDto();
        try {
            // 1. 检查考试状态
            String currentStatus = examinationmanagementMapper.getExamStatus(pub.getExamId());
            if (!"待发布".equals(currentStatus)) {
                result.setSuccess(false);
                result.setMessage("考试状态不正确，当前状态：" + currentStatus);
                return result;
            }

            // 2. 更新考试状态为待开始
            boolean updateSuccess = updateExamStatus("待开始", pub.getExamId());
            if (!updateSuccess) {
                result.setSuccess(false);
                result.setMessage("更新考试状态失败");
                return result;
            }
            long i = 0;
            // 3. 根据目标类型处理发布
            if ("student".equals(pub.getTarget_type())) {
                // 直接发布给指定学生
                if (!pub.getTarget_id().isEmpty()) {
                    examinationmanagementMapper.insertExam_student(pub.getExamId(), pub.getTarget_id());
                    //更新exam表里面的应参加人数为传递过来的学生ID的数量，一个ID代表一个学生，并且需要去重计算人数
                    //获取pub里面的学生ID列表去重数量
                    Set<String> set = new LinkedHashSet<>(pub.getTarget_id());
                    int uniqueCount = set.size(); // 提取去重后的数量
                    //更新exam表里面的应参加人数
                    examinationmanagementMapper.updateexpected_participants(pub.getExamId(), uniqueCount);
                    i = 1;
                }
            } else {
                // 发布给班级
                List<String> schoolNumberList = examinationmanagementMapper.getstudent_class_link(pub.getTarget_id());
                System.out.println(schoolNumberList);
                if (!schoolNumberList.isEmpty()) {
                    examinationmanagementMapper.insertExam_student(pub.getExamId(), schoolNumberList);
                    //更新exam表里面的应参加人数为传递过来的学生ID的数量，一个ID代表一个学生，并且需要去重计算人数
                    //获取pub里面的学生ID列表去重数量
                    Set<String> set = new LinkedHashSet<>(schoolNumberList);
                    int uniqueCount = set.size(); // 提取去重后的数量
                    //更新exam表里面的应参加人数
                    examinationmanagementMapper.updateexpected_participants(pub.getExamId(), uniqueCount);
                    i = 1;
                }
            }

            // 4. 异步发送邮件通知
            CompletableFuture.runAsync(() -> {
                try {
                    sendNotifications(pub);
                } catch (Exception e) {
                    System.out.println("邮件发送过程中出现异常: " + e.getMessage());
                }
            });
            if (i == 1) {
                result.setSuccess(true);
                result.setMessage("考试发布成功");
                return result;
            }
            result.setSuccess(false);
            result.setMessage("考试发布失败,该班级未查找到学生");
            return result;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("发布考试失败: " + e.getMessage());
            return result;
        }
    }

    private void sendNotifications(PubishExamDto pub) {
        // 1. 获取收件人信息
        LocalDateTime now = LocalDateTime.now();
        List<Map<String, String>> recipientsList = new ArrayList<>();
        System.out.println(recipientsList);
        if ("student".equals(pub.getTarget_type())) {
            if (!pub.getTarget_id().isEmpty()) {
                recipientsList = examinationmanagementMapper.getRecipientsEmailAndName(pub.getTarget_id());
            }
        } else {
            List<String> schoolNumberList = examinationmanagementMapper.getstudent_class_link(pub.getTarget_id());
            if (!schoolNumberList.isEmpty()) {
                recipientsList = examinationmanagementMapper.getRecipientsEmailAndName(schoolNumberList);
            }
        }

        // 2. 发送邮件
        for (Map<String, String> recipient : recipientsList) {
            String email = recipient.get("email");
            String name = recipient.get("real_name");

            if (email != null && !email.isEmpty()) {
                try {
                    mailService.sendSimpleMail(email, "[系统通知]" + name, "你有新的考试已发布,请及时登录系统查看");
                } catch (Exception e) {
                    System.out.println("发送邮件给 " + email + " 失败: " + e.getMessage());
                }
            }
        }
    }

    //根据学生school_Number来查询到需要进行并且考试时间未超过15分钟的考试
    @Override
    public List<ExamListVo> getExam(String schoolNumber) {
        //先通过schoolNumber来到exam_release表里面有关系的考试场次，如果没有就从student_class_link表里面查找这个学生对应哪个班级，通过班级来查询考试场次，如果都没有则提示暂未考试需要进行
        List<Integer> examId = examinationmanagementMapper.getExam_release(schoolNumber);
        if (!examId.isEmpty()) {
            List<ExamListVo> examListVos = new ArrayList<>();
            for (Integer exam_id : examId) {
                ExamListVo examListVo = examinationmanagementMapper.selectExamByIdForList(exam_id);
                // 设置个人考试状态
                setPersonalStatus(examListVo, schoolNumber);
                examListVos.add(examListVo);
            }
            return examListVos;
        } else {
            //通过学号去查询该学生所在的课程班级
            List<Integer> studentClassLinkClasId = examinationmanagementMapper.getStudent_class_link_clasId(schoolNumber);
            log.info("学号{}", schoolNumber);
            System.out.println("studentClassLinkClasId: " + studentClassLinkClasId);
            //将 List<Integer> studentClassLinkClasId转换成List<String>类型
            List<String> studentClassLinkClasIdStr = studentClassLinkClasId.stream()
                    .map(String::valueOf)
                    .collect(Collectors.toList());
            //通过班级ID列表来查询考试场次
            log.info("班级ID列表: " + studentClassLinkClasIdStr);
            if (studentClassLinkClasIdStr.isEmpty() || studentClassLinkClasIdStr.size() == 0) {
                throw new BusinessException(500, "该学生未加入任何班级");
            }
            List<Integer> examId_One = examinationmanagementMapper.getExam_releaseList(studentClassLinkClasIdStr);
            System.out.println("examId_One: " + examId_One);
            List<ExamListVo> examListVos = new ArrayList<>();
            for (Integer exam_id : examId_One) {
                ExamListVo examListVo = examinationmanagementMapper.selectExamByIdForList(exam_id);
                // 设置个人考试状态
                setPersonalStatus(examListVo, schoolNumber);
                examListVos.add(examListVo);
            }
            return examListVos;
        }
    }
    
    /**
     * 设置学生个人考试状态
     * @param examListVo 考试信息
     * @param schoolNumber 学生学号
     */
    private void setPersonalStatus(ExamListVo examListVo, String schoolNumber) {
        // 获取学生的考试记录
        ExamRecord examRecord = examinationmanagementMapper.getStudentExamRecord(examListVo.getExamId(), schoolNumber);
        
        // 如果有考试记录，使用考试记录的状态
        if (examRecord != null) {
            examListVo.setPersonalStatus(examRecord.getStatus());
        } else {
            // 如果没有考试记录，使用考试的全局状态
            examListVo.setPersonalStatus(examListVo.getStatus());
        }
    }

    //通过考试id(examId)去查询到具体的考试试题
    @Override
    public ExamQuestionVO getExamQuestion(Integer examId) {
        // 1. 获取试题列表
        List<Question_onlineExamVO> questions = examinationmanagementMapper.getExamQuestionList(examId);

        // 2. 处理每道题的选项
        questions.forEach(this::processOptions);

        // 3. 设置题号
        Map<String, Integer> typeOrderMap = new HashMap<>();
        questions.forEach(question -> {
            String type = question.getType();
            typeOrderMap.putIfAbsent(type, 0);
            int currentOrder = typeOrderMap.get(type) + 1;
            typeOrderMap.put(type, currentOrder);
            question.setScore(currentOrder);  // 设置当前题型的第几题
        });

        // 4. 设置每种题型的总数
        Map<String, Long> typeCountMap = questions.stream()
                .collect(Collectors.groupingBy(Question_onlineExamVO::getType, Collectors.counting()));
        questions.forEach(q -> q.setOrderNum(typeCountMap.get(q.getType()).intValue()));

        // 5. 获取考试信息
        Exam exam = examinationmanagementMapper.getExamById(examId);
        if (exam == null) {
            return null;
        }

        // 6. 构建返回对象
        ExamQuestionVO examQuestionVO = new ExamQuestionVO();
        examQuestionVO.setExamName(exam.getSubject() + exam.getExamName());
        examQuestionVO.setTotalScore(exam.getTotalScore());
        examQuestionVO.setDuration(exam.getDuration());
        examQuestionVO.setQuestions(questions);
        examQuestionVO.setStartTime(exam.getStartTime());
        return examQuestionVO;
    }

    //考生的答案提交f
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String submitAnswer(AnswerDto answerDto) {
        String message = "数据无效";
        if (answerDto == null) {
            return message;
        }
        System.out.println("answerDto: " + answerDto.toString());
        if (answerDto.getAnswers() == null || answerDto.getAnswers().isEmpty()) {
            message = "请填写答案";
            return message;
        }
        // 将StudentAnswer转换为StudentAnswerEntity
        List<StudentAnswerEntity> studentAnswerEntities = new ArrayList<>();
        for (StudentAnswer studentAnswer : answerDto.getAnswers()) {
            StudentAnswerEntity entity = new StudentAnswerEntity();
            entity.setExamId(answerDto.getExamId());
            entity.setSchoolNumber(answerDto.getSchoolNumber());
            entity.setQuestionId(studentAnswer.getQuestionId());
            entity.setStudentAnswer(studentAnswer.getStudentAnswer());

            // 统一处理题型
            String questionType = studentAnswer.getQuestionType();
            System.out.println("questionType: " + questionType);
            if ("单选题".equals(questionType) || "多选题".equals(questionType) || "判断题".equals(questionType) || "填空题".equals(questionType)) {
                entity.setQuestionType("客观题");
            } else {
                entity.setQuestionType("主观题");
            }
            // 设置得分
            entity.setScore(getScore(studentAnswer, answerDto));
            entity.setSubmitTime(LocalDateTime.now());
            studentAnswerEntities.add(entity);
        }
        // 将转换后的StudentAnswerEntity批量插入到数据库
        //答案提交
        int result = 0;
        for (StudentAnswerEntity studentAnswerEntity : studentAnswerEntities) {
            result = examinationmanagementMapper.insertStudentAnswer(studentAnswerEntity);
            System.out.println("result: " + result);
            if (result == 0) {
                message = "插入失败";
                return message;
            }

        }
        //插入到exam_record（考试记录表）
        //获取该学生的客观题总分
        Integer total_objective_score = examinationmanagementMapper.getTotal_objective_score(answerDto.getSchoolNumber(), answerDto.getExamId());
        // 如果为空，默认为 0
        int totalObjectiveScoreValue = total_objective_score == null ? 0 : total_objective_score;
        System.out.println(answerDto.getSchoolNumber());
        System.out.println(answerDto.getExamId());
        System.out.println("客观题总分: " + totalObjectiveScoreValue);
        //生成 NanoID
        char[] alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
        int length = 8;
        String nanoIdCustom = NanoIdUtils.randomNanoId(NanoIdUtils.DEFAULT_NUMBER_GENERATOR, alphabet, length);
        String uniqueIdentifier = answerDto.getSchoolNumber() + "_" + answerDto.getExamId() + "_" + nanoIdCustom;
        System.out.println("自定义 NanoID: " + uniqueIdentifier);
        //总分
        Integer total_score = totalObjectiveScoreValue + 0;
        int rows = examinationmanagementMapper.insertExamRecord(
                answerDto.getExamId(),
                answerDto.getSchoolNumber(),
                totalObjectiveScoreValue,
                0,
                total_score,
                "已提交",
                LocalDateTime.now(), // 当前时间
                uniqueIdentifier
        );
        //更新exam里面的submitted_participants（交卷人数）
        int updateRows = examinationmanagementMapper.updateExamSubmittedParticipants(answerDto.getExamId());
        if (rows > 0 && updateRows > 0) {
            return uniqueIdentifier;
        } else {
            throw new RuntimeException("插入考试记录失败");
        }
    }


    //查询主观题
    @Override
    public List<Subjective_questionVo> seletQuery_subjective(Integer examID, String studentID) {
        // 如果传入学号，直接使用该学号；否则查询所有参与考试的学生ID
        List<String> studentlistID = new ArrayList<>();
        if (studentID != null && !studentID.isEmpty()) {
            studentlistID.add(studentID);
            // 检查该学号是否参与了考试
            if (!examinationmanagementMapper.seletExam_record_student_id(examID).contains(studentID)) {
                return new ArrayList<>();
            }
        } else {
            studentlistID = examinationmanagementMapper.seletExam_record_student_id(examID);
        }

        System.out.println("studentlistID: " + studentlistID);

        List<Subjective_questionVo> questionVOList = new ArrayList<>();
        for (String stuID : studentlistID) {
            // 查询该学生的主观题答案
            List<Subjective_questionEntity> answers = examinationmanagementMapper.getSubjectiveAnswers(examID, stuID);
            for (Subjective_questionEntity answer : answers) {
                // 查询该题的分值
                Map<String, Object> questionScore = examinationmanagementMapper.select_exam_question_answer(answer.getQuestionId(), examID);
                System.out.println("questionScore: " + questionScore);
                Integer scoreValue = (Integer) questionScore.get("score");
                answer.setQuestionScore(scoreValue);
                // 查询题目内容
                String questionContent = examinationmanagementMapper.getQuestionContent(answer.getQuestionId());
                System.out.println("questionContent: " + questionContent);
                // 封装返回对象
                Subjective_questionVo questionVO = new Subjective_questionVo(
                        answer.getAnswerId(),
                        answer.getExamId(),
                        answer.getSchoolNumber(),
                        answer.getQuestionId(),
                        answer.getStudentAnswer(),
                        answer.getScore(),
                        answer.getSubmitTime(),
                        answer.getQuestionScore(),
                        questionContent,
                        questionScore.get("answer").toString()
                );
                questionVOList.add(questionVO);
            }
        }
        System.out.println("questionVOList: " + questionVOList);
        return questionVOList;
    }

    //人工评卷后对其数据库更新
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateExamStatus(List<SubjectiveAnswerDto> subjectiveAnswerDtoList) {
        String status = "已批改";
        // 批量更新 student_answer 表
        int result = examinationmanagementMapper.updatestudent_answer_batch(subjectiveAnswerDtoList);
        // 遍历主观题列表，累加分数
        int sumScore = 0;
        for (SubjectiveAnswerDto dto : subjectiveAnswerDtoList) {
            sumScore += dto.getScore(); // 累加分数
        }
        System.out.println("sumScore: " + sumScore);
        SubjectiveAnswerDto subjectiveAnswerDto = new SubjectiveAnswerDto();
        //将 SubjectiveAnswerDtoList 转换为 SubjectiveAnswerDto
        for (SubjectiveAnswerDto dto : subjectiveAnswerDtoList) {
            subjectiveAnswerDto.setAnswerId(dto.getAnswerId());
            subjectiveAnswerDto.setExamId(dto.getExamId());
            subjectiveAnswerDto.setSchoolNumber(dto.getSchoolNumber());
            subjectiveAnswerDto.setQuestionId(dto.getQuestionId());
            subjectiveAnswerDto.setScore(sumScore);
        }
        System.out.println("subjectiveAnswerDto: " + subjectiveAnswerDto);
        if (result > 0) {
            // 更新 exam_record 表
            int rows = examinationmanagementMapper.updateSubjectiveScore(status, subjectiveAnswerDto.getScore(), subjectiveAnswerDto.getExamId(), subjectiveAnswerDto.getSchoolNumber());
            Integer s = 0;
            if (rows > 0) {
                //执行错题记录程序
                s = getProcessedMistakes(subjectiveAnswerDto.getExamId(), subjectiveAnswerDto.getSchoolNumber());

            }
            if (s > 0 && rows > 0) {
                return true;
            }
        }
        return false;
    }

    //获取当前考试该学生的错题记录
    private Integer getProcessedMistakes(Integer examId, String schoolNumber) {
        System.out.println("\033[35m执行了吗?");
        Integer i = 0;
        Integer s = 0;
        // 获取最新考试错题集合（B）
        List<StudentMistakeEntity> studentMistakeEntities = examinationmanagementMapper.setAlistwrongquestions(examId, schoolNumber);
        // 获取历史错题集合（A）
        List<StudentMistakeEntity> studentMistakeEntities1 = examinationmanagementMapper.selectmistake_collection(schoolNumber);

        // 创建一个Map来存储历史错题，key为复合键（questionId + studentId）
        Map<String, StudentMistakeEntity> existingMistakes = studentMistakeEntities1.stream()
                .collect(Collectors.toMap(
                        a -> a.getQuestionId() + "_" + a.getStudentId(),
                        a -> a
                ));

        // 处理所有最新考试的错题
        for (StudentMistakeEntity newMistake : studentMistakeEntities) {
            String key = newMistake.getQuestionId() + "_" + newMistake.getStudentId();
            StudentMistakeEntity existingMistake = existingMistakes.get(key);

            ProcessedMistakeVO processedMistake;
            if (existingMistake != null) {
                // 如果存在重复记录，增加错误次数并连接学生答案
                processedMistake = new ProcessedMistakeVO(
                        newMistake.getMistakeId(),
                        newMistake.getStudentId(),
                        newMistake.getQuestionId(),
                        newMistake.getQuestionContent(),
                        existingMistake.getStudentAnswer() + "&" + newMistake.getStudentAnswer(),
                        newMistake.getStandardAnswer(),
                        existingMistake.getMistakeCount() + 1,
                        existingMistake.getMistakeTime(),
                        LocalDateTime.now(),
                        "未掌握"
                );
            } else {
                // 新错题
                processedMistake = new ProcessedMistakeVO(
                        newMistake.getMistakeId(),
                        newMistake.getStudentId(),
                        newMistake.getQuestionId(),
                        newMistake.getQuestionContent(),
                        newMistake.getStudentAnswer(),
                        newMistake.getStandardAnswer(),
                        1,
                        LocalDateTime.now(),
                        LocalDateTime.now(),
                        "未掌握"
                );
            }

            // 直接插入或更新到mistake_collection表
            if (existingMistake != null) {
                // 更新已存在的记录
                i = examinationmanagementMapper.updateMistakeCollection(processedMistake);
            } else {
                // 插入新记录
                s = examinationmanagementMapper.insertMistakeCollection(processedMistake);
            }
        }

        if (i > 0 || s > 0) {
            return 1;
        }
        return 0;
    }


    //处理每道题的选项
    private void processOptions(Question_onlineExamVO question) {
        if ("填空题".equals(question.getType()) || "问答题".equals(question.getType())) {
            question.setOptions(null);
            return;
        }

        try {
            JsonNode optionsNode = objectMapper.readTree(question.getOptionsJson());
            List<OptionVO> options = new ArrayList<>();
            char label = 'A';

            for (JsonNode node : optionsNode) {
                String content = node.asText();
                // 只添加非空选项
                if (content != null && !content.trim().isEmpty()) {
                    options.add(new OptionVO(String.valueOf(label), content));
                }
                label++;
            }
            question.setOptions(options);
        } catch (Exception e) {
            e.printStackTrace();
            question.setOptions(new ArrayList<>());
        }
    }


    //创建一个更新状态的方法
    public boolean updateExamStatus(String status, Integer examId) {
        int i = examinationmanagementMapper.updateExamStatus(status, examId);
        if (i > 0) {
            return true;
        }
        return false;
    }


    //客观题计算分数
    public Integer getScore(StudentAnswer studentAnswer, AnswerDto answerDto) {
        Integer score = 0;
        if (studentAnswer.getQuestionType().equals("问答题") || studentAnswer.getQuestionType().equals("简答题")) {
            return score;
        }

        // 初始化 questionAnswerStr
        Map<String, Object> questionAnswerStr = null;

        try {
            // 获取题目ID和学生答案
            Integer questionId = studentAnswer.getQuestionId();
            String studentAnswerStr = studentAnswer.getStudentAnswer();

            // 查询题目答案
            questionAnswerStr = examinationmanagementMapper.select_exam_question_answer(questionId, answerDto.getExamId());

            if (questionAnswerStr == null) {
                System.err.println("未找到题目ID：" + questionId + " 对应的答案数据");
                return score; // 返回默认分数 0
            }

            // 比较学生答案与正确答案
            String correctAnswer = String.valueOf(questionAnswerStr.get("answer"));
            if (studentAnswerStr != null && studentAnswerStr.equals(correctAnswer)) {
                score = (Integer) questionAnswerStr.get("score");
            }

            // 打印调试信息
            System.out.println("题目ID：" + questionId + " 学生答案：" + studentAnswerStr + " 正确答案：" + correctAnswer + " 分数：" + questionAnswerStr.get("score"));
            System.out.println("最终得分：" + score);

        } catch (Exception e) {
            System.err.println("获取分数时发生异常：" + e.getMessage());
            e.printStackTrace();
        }

        return score;
    }

    @Override
    public List<Class> getTeacherClasses(String teacherId) {
        List<Class> allClasses = examinationmanagementMapper.getTeacherClasses(teacherId);
        // 过滤掉没有学生的班级
        return allClasses.stream()
                .filter(clazz -> {
                    List<String> students = examinationmanagementMapper.getstudent_class_link(Collections.singletonList(String.valueOf(clazz.getClassId())));
                    return !students.isEmpty();
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<StudentVO> getTeacherStudents(String teacherId) {
        return examinationmanagementMapper.getTeacherStudents(teacherId);
    }

    @Override
    public List<QuestionPreviewVo> getExamPreview(Integer examId) {
        // 根据考试ID查询考试中的题目ID列表
        List<Integer> questionIds = examinationmanagementMapper.getQuestionIdsByExamId(examId);

        if (questionIds == null || questionIds.isEmpty()) {
            return Collections.emptyList(); // 如果没有题目，返回空列表
        }

        List<QuestionPreviewVo> previewList = new ArrayList<>();

        // 遍历题目ID列表，获取每个题目的详细信息
        for (Integer questionId : questionIds) {
            Question question = examinationmanagementMapper.getQuestionById(questionId);
            //通过试题id和考试ID双验证查询分值
            Integer score = examinationmanagementMapper.getQuestionScore(questionId, examId);
            if (question != null) {
                // 将Question对象转换为QuestionPreviewVo对象
                QuestionPreviewVo previewVo = new QuestionPreviewVo();
                previewVo.setType(question.getType());
                previewVo.setContent(question.getContent());
                previewVo.setScore(score);

                previewList.add(previewVo);
            }
        }

        return previewList;
    }

    // 获取老师创建的考试
    @Override
    public List<ExamVO> getteacherIdExam(String teacherId, String status, Integer pageNum, Integer pageSize, String searchText) {
        // 使用PageHelper进行分页
        PageHelper.startPage(pageNum, pageSize);
        // 调用mapper方法，传入searchText参数
        List<ExamVO> examList = examinationmanagementMapper.getteacherIdExam(teacherId, status, searchText);
        // 获取分页信息
        PageInfo<ExamVO> pageInfo = new PageInfo<>(examList);
        // 设置总条数到第一个元素中
        if (!examList.isEmpty()) {
            ExamVO firstExam = examList.get(0);
            firstExam.setTotal(pageInfo.getTotal());
        }
        return examList;
    }

    @Override
    public ExamVO getExamDetail(Integer examId) {
        ExamVO examVO = examinationmanagementMapper.getExamDetail(examId);
        if (examVO != null) {
            // 获取试题列表
            List<QuestionPreviewVocopy> questions = examinationmanagementMapper.getExamQuestions(examId);
            examVO.setQuestionList(questions);
        }
        return examVO;
    }

    @Override
    public boolean updateExamInfo(Exam exam) {
        return examinationmanagementMapper.updateExamInfo(exam) > 0;
    }

    @Override
    public List<QuestionVO> getQuestionBanks(String teacherId) {
        return examinationmanagementMapper.getQuestionBanks(teacherId);
    }

    @Override
    public List<Question> getQuestionsByBank(String questionBankName) {
        return examinationmanagementMapper.getQuestionsByBank(questionBankName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addExamQuestions(AddExamQuestionRequest request) {
        if (request == null || request.getExamId() == null || request.getQuestions() == null || request.getQuestions().isEmpty()) {
            return false;
        }

        // 批量插入试题
        for (AddExamQuestionRequest.ExamQuestionItem question : request.getQuestions()) {
            examinationmanagementMapper.insertExamQuestion(request.getExamId(), question.getQuestionId(), question.getScore());
        }

        return true;
    }

    //删除试题
    @Override
    public void deleteQuestion(Integer examId, Integer questionId) {
        // 检查考试是否存在
        ExamQuestion examQuestion = examinationmanagementMapper.selectByExamAndQuestionId(examId, questionId);
        if (examQuestion == null) {
            throw new RuntimeException("试题不存在于该考试中");
        }
        // 删除考试试题关联
        examinationmanagementMapper.deleteByExamAndQuestionId(examId, questionId);
    }

    //删除试卷
    @Override
    @Transactional
    public void deleteExams(List<Integer> examIds) {
        if (examIds == null || examIds.isEmpty()) {
            throw new IllegalArgumentException("考试ID列表不能为空");
        }

        for (Integer examId : examIds) {
            // 1. 删除考试-试题关联
            examinationmanagementMapper.deleteExamQuestions(examId);

            // 2. 删除考试-发布关联
            examinationmanagementMapper.deleteExamReleases(examId);

            // 3. 删除考试记录
            examinationmanagementMapper.deleteExamRecords(examId);

            // 4. 删除考试基本信息
            examinationmanagementMapper.deleteExam(examId);
        }
    }

    //获取最近考试
    @Override
    public List<Exam> getRecentExams(String schoolNumber) {
        // 获取最近5场考试
        return examinationmanagementMapper.selectRecentExams(schoolNumber);
    }

    //获取考生已经作答的考试
    @Override
    public List<ExamRecordoneVO> getExamstudentAnswer(String schoolNumber) {
        List<ExamRecordoneVO> examRecordEntities = examinationmanagementMapper.getExamstudentAnswer(schoolNumber);
        return examRecordEntities;
    }

    @Override
    public Boolean updateExamStatusNull(String examId, String schoolNumber) {
        Integer i = examinationmanagementMapper.updateExamStatusNull(examId, schoolNumber);
        if (i > 0) {
            return true;
        }
        return false;
    }


}




